<template>
  <div>
    <div class="se-search">
      <input v-model="keyword" class="se-search-input" type="text" placeholder="输入城市名或拼音" />
    </div>
    <!--输入框列表选项-->
    <div class="se-search-content" ref="search" v-show="keyword">
      <ul>
        <li
          class="search-content border-bottom"
          v-for="(item) in citiesList"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >{{item.name}}</li>
        <li class="search-content border-bottom" v-show="hasNoData">没有匹配到的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapActions } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data: function () {
    return {
      keyword: '',
      citiesList: [],
      timer: null
    }
  },
  computed: {
    hasNoData: function () {
      return !this.citiesList.length
    }
  },
  // 监听输入框里面输入的值的变化
  watch: {
    keyword: function () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.citiesList = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let key in this.cities) {
          this.cities[key].forEach((value) => {
            // indexOf(key)返回的是key出现的下标
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              // {"id": 56,"spell": "aba","name": "阿坝"} 这每个对象添加到result
              result.push(value)
            }
          })
        }
        this.citiesList = result
      }, 100)
    }
  },
  methods: {
    handleCityClick: function (cityName) {
      // 在组件里面通过dispatch函数来调用Actions
      // this.$store.dispatch('changeCity', cityName)
      this.changeCity(cityName)
      // 我们使用router，每个vue实例组件都有$router属性
      this.$router.push('/')
    },
    ...mapActions(['changeCity'])
  },
  mounted: function () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl';

.se-search {
  height: 0.76rem;
  padding: 0 0.1rem;
  background: $bgColor;

  .se-search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    padding: 0 0.1rem;
    line-height: 0.62rem;
    text-align: center;
    border-radius: 0.1rem;
    color: #666;
  }
}

.se-search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;

  .search-content {
    line-height: 0.56rem;
    padding-left: 0.2rem;
    color: #666;
  }
}
</style>
